package org.xxkk.util;

import java.io.*;
import java.net.URL;

/**
 * @author xxkk
 * @version 1.0.0
 * @title FileUtil
 * @description ʕ•ᴥ•ʔ
 * @create 2025/1/10 20:53
 **/
public class FileUtil {
    public static void main(String[] args) {
        String filePath = "example.txt";
        String dataToWrite = ResourcesRootPathUtil.getUserDir();
        // 写入数据到文件
        writeToFile(filePath, dataToWrite);
        // 从文件读取数据
        String dataRead = readFromFile(filePath);
        System.out.println(dataRead);
    }

    public static void writeToFile(String filePath, String data) {
//       FileWriter writer_ = new FileWriter(filePath);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFromFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists())
            return null;
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return contentBuilder.toString();
    }
}
